package com.xiaochang.em.utils;

import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
import com.univocity.parsers.csv.CsvParser;
import com.univocity.parsers.common.processor.BeanListProcessor;
import com.univocity.parsers.csv.CsvFormat;
import com.univocity.parsers.csv.CsvParserSettings;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collections;
import java.util.List;

@Component
@Slf4j
public class CSVUtils {

    /**
     * 读取crv文件并转换成List
     *
     * @param clazz  bean对象
     * @param file   待读取文件
     * @return crv对象list
     */
    public static <T> List<T> read(MultipartFile file, Class<T> clazz, String charset) {

        List<T> result = Collections.emptyList();
        try {
            BeanListProcessor<T> rowProcessor = new BeanListProcessor<>(clazz);

            InputStream in = file.getInputStream();
//            InputStreamReader reader = new InputStreamReader(in, "GBK");
            InputStreamReader reader = new InputStreamReader(in, charset);

            CsvParserSettings settings = new CsvParserSettings();
            settings.getFormat().setLineSeparator("\n");
            settings.setProcessor(rowProcessor);
            settings.setFormat(new CsvFormat());

            CsvParser parser = new CsvParser(settings);
            parser.parse(reader);
            //逐行读取
            result = rowProcessor.getBeans();
        } catch (Exception e) {
            log.error("Import csv file failed. message: ", e);
        }
        return result;
    }

    /**
     * 获取CSV文件编码格式
     * @param inputStream
     * @return
     * @throws IOException
     */
    public static String getCsvCharset(InputStream inputStream) throws IOException {
        String charset = null;
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            CharsetDetector cd = new CharsetDetector();
            cd.setText(bis);
            CharsetMatch cm = cd.detect();
            if (cm != null) {
                charset = cm.getName();
            } else {
                throw new UnsupportedCharsetException("获取文件编码失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(e);
        }finally {
            if (null != bis) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != inputStream) {
                inputStream.close();
            }
        }

        return charset;
    }
}
